package com.project.study.farming.common.utils;

import cn.hutool.core.util.StrUtil;
import com.project.study.farming.common.mapper.BaseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * bean操作类
 * @since 2020-04-11
 */
@Component
public class BeanMapper {

    @Autowired
    private BaseMapper baseMapper;

    public <T> Integer insert(T t){
        String sql = SqlUtil.insert(t);
        this.baseMapper.insert(sql);
        sql = SqlUtil.getId(t.getClass());
        return this.baseMapper.selectId(sql);
    }

    public <T> void updateById(T t){
        this.baseMapper.update(SqlUtil.updateById(t));
    }

    public <T> T selectOne(Class<T> cls, String whereSql){
        String sql = SqlUtil.select(cls);
        sql = StrUtil.isNotBlank(whereSql) ? String.format("%s where %s", sql, whereSql) : sql;
        List<Map<String, Object>> res = this.baseMapper.select(sql);
        return Objects.nonNull(res) && !res.isEmpty() ? CommonUtil.transTo(res.get(0), cls) : null;
    }

    public <T> List<T> selectList(Class<T> cls){
        return this.selectList(cls, StrUtil.EMPTY);
    }

    public <T> List<T> selectList(Class<T> cls, String whereSql){
        String sql = SqlUtil.select(cls);
        sql = StrUtil.isNotBlank(whereSql) ? String.format("%s where %s", sql, whereSql) : sql;
        List<Map<String, Object>> res = this.baseMapper.select(sql);
        return Objects.nonNull(res) && !res.isEmpty() ? res.stream().map(t -> CommonUtil.transTo(t, cls)).collect(Collectors.toList()) : new ArrayList<>();
    }
}
